import React, { useEffect, useState } from "react";

import "./index.scss";

export enum FilterType {
  TYPE_STRING = "TYPE_STRING",
  TYPE_NUMBER = "TYPE_NUMBER",
  TYPE_SELECT = "TYPE_SELECT",
}

type FilterConfig = {
  type: FilterType;
  key: string;
  placeholder: string;
  options?: string[];
  callback?: () => void;
};

type IProps = {
  width?: number | string;
  filters: FilterConfig[];
  dataArr: Record<string, any>[];
  onDataFiltered: (newArr: Record<string, any>[]) => void;
  devMode?: boolean;
};

const StoFilter: React.FC<IProps> = ({
  width = "100%",
  filters,
  dataArr,
  onDataFiltered,
  devMode = true,
}) => {
  const [data, setData] = useState(dataArr);
  const [theFilters, setTheFilters] = useState(filters);

  const renderFilters = ({
    type,
    key,
    placeholder,
    options,
    callback,
  }: FilterConfig) => {
    switch (type) {
      case FilterType.TYPE_STRING:
        return (
          <input
            className={"item " + ("el-" + key)}
            type="text"
            placeholder={placeholder}
          />
        );

      case FilterType.TYPE_NUMBER:
        return (
          <div className="item range-box">
            <input
              className={"el-" + key}
              type="number"
              placeholder={`最小${placeholder}`}
            />
            <span>-</span>
            <input
              className={"el-" + key}
              type="number"
              placeholder={`最大${placeholder}`}
            />
          </div>
        );

      case FilterType.TYPE_SELECT:
        return (
          <select className={"item " + ("el-" + key)} name="">
            <option value="">请选择{placeholder}</option>
            {options?.map((op) => (
              <option value={op}>{op}</option>
            ))}
          </select>
        );

      default:
        return <div>非法过滤器</div>;
    }
  };

  const onFilter = () => {
    const farr = dataArr.filter((item) => {
      /* 测试是否满足所有过滤规则 */
      for (let i = 0; i < theFilters.length; i++) {
        const { type, key } = theFilters[i];
        let [el0, el1] = document.querySelectorAll(".el-" + key);

        /* 当前规则用户未输入 */
        if (
          (el0 as any).value === "" ||
          ((el0 as any).value as string).startsWith("请选择")
        ) {
          continue;
        }

        if (el1 && !(el1 as HTMLInputElement).value) {
          continue;
        }

        switch (type) {
          case FilterType.TYPE_STRING:
            if (!item[key].includes((el0 as HTMLInputElement).value))
              return false;
            break;

          case FilterType.TYPE_NUMBER:
            if (
              !(
                item[key] >= (el0 as HTMLInputElement).value &&
                item[key] <= (el1 as HTMLInputElement).value
              )
            )
              return false;
            break;

          case FilterType.TYPE_SELECT:
            if (item[key] !== (el0 as HTMLSelectElement).value) return false;
            break;

          default:
            break;
        }
      }

      return true;
    });

    setData(farr);
    onDataFiltered(farr);
  };

  const onReset = () => {
    console.log("onReset");
    // setTheFilters(filters);
    window.location.reload();
  };

  // useEffect(() => {
  //   console.log("theFilters updated");
  // }, [theFilters]);

  return (
    <>
      <div className="wrapper-sto-filter-root" style={{ width }}>
        <div className="wrapper-sto-filter">
          {/* 字符串-模糊搜索 */}
          {/* <input className="item" type="text" placeholder="请输入用户姓名" /> */}

          {/* 枚举-下拉过滤 */}
          {/* <select className="item" name="sel-x" id="">
        <option value="">请选择性别</option>
        <option value="">A</option>
        <option value="">B</option>
        <option value="">C</option>
      </select> */}

          {/* 数值-范围过滤 */}
          {/* <div className="item range-box">
        <input type="number" placeholder="最小年龄" />
        <span>-</span>
        <input type="number" placeholder="最大年龄" />
      </div> */}

          {theFilters.map((config) => renderFilters(config))}

          {/* 空白 */}
          <div className="item"></div>

          {/* 搜索 + 重置 */}
          <div className="item btns">
            <button onClick={onFilter}>搜索</button>
            <button onClick={onReset}>重置</button>
          </div>
        </div>
      </div>

      {devMode && (
        <div style={{ width: "100%", textAlign: "left", marginTop: 10 }}>
          {JSON.stringify(data)}
        </div>
      )}

    </>
  );
};

export default StoFilter;
